package com.infore.airsupervise.utils;

import android.content.Context;
import android.content.res.TypedArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.infore.airsupervise.R;

/**
 * TitleBar的帮助类
 *
 * @features: 把用户定义的View和TitleBar依次添加到ViewGroup中
 * @author: Ding Xinlin
 * @date: 2017/03/02 10:43
 */
public class TitleBarHelper {

    private Context mContext;
    private LayoutInflater mInflater;

    private FrameLayout mContentView;
    private View mUserView;
    private View titleBar;

    /*
    * 1、toolbar是否悬浮在窗口之上
    * 2、toolbar的高度获取
    * */
    private static int[] ATTRS = {
            R.attr.windowActionBarOverlay,
            R.dimen.title_bar_height
    };

    public TitleBarHelper(Context context, int layoutId) {
        this.mContext = context;
        mInflater = LayoutInflater.from(mContext);
        // 初始化主容器
        initContentView();
        // 初始化用户定义的布局
        initUserView(layoutId);
        // 初始化TitleBar
        initTitleBar();
    }

    /**
     * 初始化主容器
     */
    private void initContentView() {
        // 直接创建一个帧布局，作为视图容器的父容器
        mContentView = new FrameLayout(mContext);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        mContentView.setLayoutParams(params);
        // 使不被状态栏遮挡
        mContentView.setFitsSystemWindows(true);
    }

    /**
     * 初始化toolbar
     */
    private void initTitleBar() {
        titleBar = mInflater.inflate(R.layout.common_titlebar, mContentView);
    }

    /**
     * 初始化用户定义的布局
     * @param id
     */
    @SuppressWarnings("ResourceType")
    private void initUserView(int id) {
        mUserView = mInflater.inflate(id, null);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        TypedArray typedArray = mContext.getTheme().obtainStyledAttributes(ATTRS);
        // 获取主题中定义的悬浮标志
        boolean overly = typedArray.getBoolean(0, false);
        // 获取主题中定义的TitleBar的高度
        int toolBarSize = (int) typedArray.getDimension(
                1, (int) mContext.getResources().getDimension(R.dimen.title_bar_height));
        typedArray.recycle();
        // 如果是悬浮状态，则不需要设置间距
        params.topMargin = overly ? 0 : toolBarSize;
        mContentView.addView(mUserView, params);
    }

    public FrameLayout getContentView() {
        return mContentView;
    }

    public View getTitleBar() {
        return titleBar;
    }
}
